﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using BbsbWebService.Enums;
using BbsbWebService.Repositories;

namespace BbsbWebService.Classes
{
    [DataContract]
    public class Group : BaseGroup
    {
        [DataMember]
        public StateItem[] Items
        {
            get
            {
                if (EditedGroupItems != null &&
                    EditedGroupItems.Any())
                {
                    return EditedGroupItems.ToStateArray();
                }
                else
                {
                    return GroupItems.ToStateArray();
                }
            }
            set
            {
                if (value != null)
                {
                    List<ControllableItem> items = new List<ControllableItem>();
                    foreach (var item in value)
                    {
                        if (item != null)
                        {
                            var contItem = RepositoryInstances.ItemRepository.GetItem(item.Id);
                            items.Add(contItem);
                        }
                    }
                    EditedGroupItems = items;
                }
            }
        }

        public IEnumerable<ControllableItem> EditedGroupItems { get; set; }

        public IEnumerable<ControllableItem> GroupItems
        {
            get
            {
                return RepositoryInstances.ItemRepository.Items.Where(o => o.Groups.Any(p => p.Id == this.Id));
            }
        }

        public IEnumerable<ControllableItem> NotGroupItems
        {
            get
            {
                return RepositoryInstances.ItemRepository.Items.Where(o => !o.Groups.Any(p => p.Id == this.Id));
            }
        }

        #region ICloneable Members

        public Group Clone()
        {
            Group group = new Group();
            group.Id = this.Id;
            group.Name = this.Name;
            group.Type = this.Type;

            return group;
        }

        #endregion
    }
}
